/**
 * Created by 鹏 on 14-3-11.
 */
var installService = require('../service/installService');
var userService = require('../service/userService');
var enums = require('../common/enum');

exports.index = function (req, res) {
    var config = installService.getConfig();
    if (config != null && config.Install) {
        res.redirect('/Installed');
    }
    else {
        res.render('install');
    }
};

exports.install = function (req, res) {
    var config = installService.getConfig();
    if (config.Install) {
        res.redirect('/Installed');
    }
    config.Install = true;
    config.MySqlHost = req.param("MySqlHost");
    config.MySqlPort = req.param("MySqlPort");
    config.MySqlDatabase = req.param("MySqlDatabase");
    config.MySqlUser = req.param("MySqlUser");
    config.MySqlPass = req.param("MySqlPass");

    installService.testConnection(config, function (err) {
        if (err) {
            res.json({success: false, error: 1});
        }
        else {
            installService.runInstall(config, function () {
                var admin = {
                    Email: req.param("AdminEmail"),
                    Nick: "Admin",
                    Password: req.param("AdminPass"),
                    Status: enums.UserStatus.Enabled,
                    IsAdmin: enums.IsAdmin.Yes
                };
                userService.signUp(admin, function () {
                    installService.saveConfig(config);
                    req.app.set("SysConfig", config);
                    res.json({success: true});
                });
            });
        }
    });
};

exports.installed = function (req, res) {
    res.render('installed');
};